package com.study.talk.app.moment;

import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.PopupMenu;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import com.study.talk.R;
import com.study.talk.adapter.MomentGridViewAdapter;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.databinding.ActivityAddMomentBinding;
import com.study.talk.net.NetApi;
import com.study.talk.util.ActivityUtil;
import com.study.talk.util.FileUtil;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.alert.AlertUtil;

import java.util.ArrayList;
import java.util.List;

public class AddMomentActivity extends BaseActivity {


    private ActivityResultLauncher<PickVisualMediaRequest> imageChooseLauncher;
    private List<Uri> imageList;

    private Uri chooseImage;

    private ActivityAddMomentBinding activityAddMomentBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityAddMomentBinding = ActivityAddMomentBinding.inflate(getLayoutInflater());
        setContentView(activityAddMomentBinding.getRoot());
        imageList = (List<Uri>) getApp().dataMap.get("imageList");
        initView();
        imageChooseLauncher = registerForActivityResult(new ActivityResultContracts.PickMultipleVisualMedia(9), results -> {
            if (!results.isEmpty()) {
                results.add(chooseImage);
                imageList = results;
                activityAddMomentBinding.addMomentGridView.setAdapter(new MomentGridViewAdapter(imageList));
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            AlertUtil.show(AddMomentActivity.this, "退出提醒", "确认退出吗？内容不会被保存哦!", b -> {
                if (b) {
                    finish();
                }
            });
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertUtil.show(AddMomentActivity.this, "退出提醒", "确认退出吗？内容不会被保存哦!", b -> {
                if (b) finish();
            });
        }
        return false;
    }

    private void initView() {

        activityAddMomentBinding.addMomentToolbar.setNavigationOnClickListener(v -> finish());

        if (ActivityUtil.isPad(AddMomentActivity.this))
            activityAddMomentBinding.addMomentGridView.setNumColumns(9);
        chooseImage = FileUtil.getFallbackRingtoneUri(AddMomentActivity.this);
        if (getApp().dataMap.get("imageList") == null) {
            imageList = new ArrayList<>();
        } else {
            imageList = (List<Uri>) getApp().dataMap.get("imageList");
        }
        imageList.add(chooseImage);
        activityAddMomentBinding.addMomentGridView.setAdapter(new MomentGridViewAdapter(imageList));
        activityAddMomentBinding.addMomentGridView.setOnItemClickListener((parent, view, position, id) -> {
            if (position == imageList.size() - 1) {
                imageChooseLauncher.launch(new PickVisualMediaRequest.Builder()
                        .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                        .build());
            }
        });

        activityAddMomentBinding.addMomentGridView.setOnItemLongClickListener((parent, view, position, id) -> {
            if (position != imageList.size() - 1) {
                PopupMenu popupMenu = new PopupMenu(AddMomentActivity.this, view);
                popupMenu.getMenuInflater().inflate(R.menu.delete, popupMenu.getMenu());
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(item -> {
                    if (item.getItemId() == R.id.menu_delete) {
                        imageList.remove(position);
                        ((BaseAdapter) activityAddMomentBinding.addMomentGridView.getAdapter()).notifyDataSetChanged();
                    }
                    return true;
                });
            }
            return true;
        });

        //发布
        activityAddMomentBinding.addMomentBt.setOnClickListener(v -> {
            if (checkInput(activityAddMomentBinding.addMomentEditText, "请输入动态内容")) return;
            String content = activityAddMomentBinding.addMomentEditText.getText().toString();
            ArrayList<String> paths = new ArrayList<>();
            imageList.remove(imageList.size() - 1);
            for (Uri uri : imageList) {
                paths.add(FileUtil.getPathFromUri(AddMomentActivity.this, uri));
            }
            NetApi.uploadMultipleFileOther(paths, AddMomentActivity.this, photos -> {
                runOnUiThread(() -> ToastUtil.showToast(AddMomentActivity.this, "图片上传成功"));
                NetApi.addMoment(getApp().userInfo, photos, content, b -> {
                    runOnUiThread(() -> ToastUtil.showToast(AddMomentActivity.this, "发布成功"));
                    handler.postDelayed(AddMomentActivity.this::finish, 1000);
                }, msg -> runOnUiThread(() -> ToastUtil.showToast(AddMomentActivity.this, "发布失败")));
            }, msg -> runOnUiThread(() -> ToastUtil.showToast(AddMomentActivity.this, msg)));
        });
    }

    @Override
    public void onBackPressed() {
        getApp().dataMap.remove("imageList");
        super.onBackPressed();
    }


}